package stockin

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StockinDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStockinDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StockinDetailLogic {
	return &StockinDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StockinDetailLogic) StockinDetail(req *types.StockInRequest) (resp *types.StockInResponse, err error) {
	resp = new(types.StockInResponse)
	//1.入库单概要
	one, err := l.svcCtx.StockInModel.FindOne(l.ctx, req.Id)
	switch err {
	case nil:
	case model.ErrNotFound:
		resp.Code = http.StatusBadRequest
		resp.Msg = "入库单不存在"
		return resp, nil
	default:
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Data.Id = one.Id
	resp.Data.SupplierId = one.SupplierId
	resp.Data.SupplierName = one.SupplierName
	resp.Data.HasTax = one.HasTax
	resp.Data.Tax = one.Tax
	resp.Data.Total = one.Total
	resp.Data.Date = one.Date

	//2.入库单原料详情
	var details []model.StockInDetail
	details, err = l.svcCtx.StockInDetailModel.FindByPage(l.ctx, fmt.Sprintf(" where stock_id=%d", req.Id))
	switch err {
	case nil:
	case model.ErrNotFound:
	default:
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	for _, detail := range details {
		resp.Data.List = append(resp.Data.List, types.StockInDetail{
			Id:            detail.Id,
			MaterialsId:   detail.MaterialsId,
			MaterialName:  detail.MaterialsName,
			MaterialTypes: detail.MaterialsTypes,
			Weight:        detail.Weight,
			Price:         detail.Price,
		})
	}

	return resp, nil
}
